<template>
  <div class="delivery-list">
    <div class="page-header">
      <h2>配送列表</h2>
    </div>
    
    <div class="search-bar">
      <el-select v-model="searchStatus" placeholder="配送状态" clearable>
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" @click="searchDeliveries">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="deliveries"
      border
      style="width: 100%">
      <el-table-column
        prop="deliveryId"
        label="配送ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="orderId"
        label="订单ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="shippingAddress"
        label="配送地址"
        min-width="200">
      </el-table-column>
      <el-table-column
        prop="carrier"
        label="配送公司"
        width="120">
      </el-table-column>
      <el-table-column
        prop="status"
        label="配送状态"
        width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="estimatedDelivery"
        label="预计送达"
        width="120">
        <template slot-scope="scope">
          {{ scope.row.estimatedDelivery ? formatDate(scope.row.estimatedDelivery) : '无' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="actualDelivery"
        label="实际送达"
        width="120">
        <template slot-scope="scope">
          {{ scope.row.actualDelivery ? formatDate(scope.row.actualDelivery) : '未送达' }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="360">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="viewDetail(scope.row)">查看详情</el-button>
          <el-button
            size="mini"
            type="success"
            @click="updateStatus(scope.row)"
            v-if="scope.row.status !== 'delivered'">更新状态</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="viewOrder(scope.row)">查看订单</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination">
    </el-pagination>
    
    <!-- 更新配送状态对话框 -->
    <el-dialog title="更新配送状态" :visible.sync="statusDialogVisible" width="400px">
      <el-form :model="statusForm">
        <el-form-item label="配送状态" label-width="100px">
          <el-select v-model="statusForm.status" placeholder="请选择配送状态">
            <el-option
              v-for="item in deliveryStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实际送达" label-width="100px" v-if="statusForm.status === 'delivered'">
          <el-date-picker
            v-model="statusForm.actualDelivery"
            type="date"
            placeholder="选择实际送达日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitStatus">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import deliveryApi from '@/api/delivery'
import moment from 'moment'

export default {
  name: 'DeliveryList',
  
  data() {
    return {
      loading: true,
      deliveries: [],
      allDeliveries: [],
      searchStatus: '',
      statusOptions: [
        { value: 'processing', label: '处理中' },
        { value: 'shipped', label: '已发货' },
        { value: 'in_transit', label: '运输中' },
        { value: 'delivered', label: '已送达' }
      ],
      deliveryStatusOptions: [
        { value: 'processing', label: '处理中' },
        { value: 'shipped', label: '已发货' },
        { value: 'in_transit', label: '运输中' },
        { value: 'delivered', label: '已送达' }
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      statusDialogVisible: false,
      statusForm: {
        deliveryId: null,
        status: '',
        actualDelivery: null
      }
    }
  },
  
  created() {
    this.fetchDeliveries()
  },
  
  methods: {
    // 获取配送列表
    async fetchDeliveries() {
      this.loading = true
      try {
        const response = await deliveryApi.getAllDeliveries()
        this.allDeliveries = response.data
        this.filterDeliveries()
        this.loading = false
      } catch (error) {
        this.$message.error('获取配送列表失败')
        this.loading = false
      }
    },
    
    // 过滤配送
    filterDeliveries() {
      let filtered = [...this.allDeliveries]
      
      // 按状态过滤
      if (this.searchStatus) {
        filtered = filtered.filter(item => item.status === this.searchStatus)
      }
      
      this.total = filtered.length
      
      // 分页
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.deliveries = filtered.slice(start, end)
    },
    
    // 搜索配送
    searchDeliveries() {
      this.currentPage = 1
      this.filterDeliveries()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchStatus = ''
      this.currentPage = 1
      this.filterDeliveries()
    },
    
    // 查看配送详情
    viewDetail(row) {
      this.$router.push(`/deliveries/${row.deliveryId}`)
    },
    
    // 查看订单详情
    viewOrder(row) {
      this.$router.push(`/orders/${row.orderId}`)
    },
    
    // 更新配送状态
    updateStatus(row) {
      this.statusForm = {
        deliveryId: row.deliveryId,
        status: row.status,
        actualDelivery: row.status === 'delivered' ? row.actualDelivery : null
      }
      this.statusDialogVisible = true
    },
    
    // 提交配送状态
    async submitStatus() {
      try {
        // 如果是已送达状态，则更新配送信息
        if (this.statusForm.status === 'delivered') {
          const delivery = {
            deliveryId: this.statusForm.deliveryId,
            status: this.statusForm.status,
            actualDelivery: this.statusForm.actualDelivery
          }
          
          const response = await deliveryApi.updateDelivery(this.statusForm.deliveryId, delivery)
          if (response.data.success) {
            this.$message.success(response.data.message)
            this.statusDialogVisible = false
            this.fetchDeliveries()
          } else {
            this.$message.error(response.data.message)
          }
        } else {
          // 只更新状态
          const response = await deliveryApi.updateDeliveryStatus(this.statusForm.deliveryId, this.statusForm.status)
          if (response.data.success) {
            this.$message.success(response.data.message)
            this.statusDialogVisible = false
            this.fetchDeliveries()
          } else {
            this.$message.error(response.data.message)
          }
        }
      } catch (error) {
        this.$message.error('更新配送状态失败')
      }
    },
    
    // 格式化日期
    formatDate(date) {
      return moment(date).format('YYYY-MM-DD')
    },
    
    // 获取状态类型
    getStatusType(status) {
      const map = {
        'processing': 'info',
        'shipped': 'primary',
        'in_transit': 'warning',
        'delivered': 'success'
      }
      return map[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const map = {
        'processing': '处理中',
        'shipped': '已发货',
        'in_transit': '运输中',
        'delivered': '已送达'
      }
      return map[status] || status
    },
    
    // 页面大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.filterDeliveries()
    },
    
    // 页码变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.filterDeliveries()
    }
  }
}
</script>

<style scoped>
.delivery-list {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 